package com.yanqu.road.server.channelserver.timer.entername;

import com.yanqu.road.entity.activity.entername.ActivityGroupMatch;
import com.yanqu.road.pb.cross3.activity.EnterNameProto;
import com.yanqu.road.server.channelserver.logic.ChannelMessageHelper;
import com.yanqu.road.server.channelserver.manager.activity.entername.ChannelEnterNameMgr;
import com.yanqu.road.server.channelserver.manager.activity.entername.ChannelEnterNameRankMgr;
import com.yanqu.road.server.channelserver.manager.activity.entername.EnterNameActivity;
import com.yanqu.road.server.channelserver.manager.activity.entername.EnterNameModel;
import com.yanqu.road.server.channelserver.manager.activity.entername.rank.EnterNameGroupRank;
import com.yanqu.road.server.channelserver.manager.activity.entername.rank.EnterNameGroupRankModel;
import com.yanqu.road.server.channelserver.manager.activity.entername.rank.EnterNameRankModel;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.executor.GeneralTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ChannelEnterNameTask extends GeneralTask {

    private static final Logger logger = LogManager.getLogger(ChannelEnterNameTask.class.getName());

    private static final List<Integer> doneDisperseGold = new ArrayList<>();

    @Override
    public void doRun() {

        for (Map.Entry<Integer, EnterNameModel> modelEntry : ChannelEnterNameMgr.getEnterNameModelMap().entrySet()) {
            try {
                modelEntry.getValue().grouping();
                //间隔3分钟
                if((System.currentTimeMillis() / (1000 * 60)) % 3 == 0) {
                    modelEntry.getValue().initCountListMsg();
                }
            }catch (Exception e){
                logger.error("activity {} grouping error , {}", modelEntry.getKey(), e.getMessage());
                logger.error(e.getMessage(), e);
            }
        }

        for (Map.Entry<Integer, Map<Integer, Map<Integer, EnterNameRankModel>>> entry : ChannelEnterNameRankMgr.getUserRankMap().entrySet()) {
            for (Map.Entry<Integer, Map<Integer, EnterNameRankModel>> enter1 : entry.getValue().entrySet()) {
                for (Map.Entry<Integer, EnterNameRankModel> modelEntry : enter1.getValue().entrySet()) {
                    try {
                        modelEntry.getValue().initListMsg();
                    }catch (Exception e){
                        logger.error("activity {} initListMsg error , {}", modelEntry.getKey(), e.getMessage());
                    }
                }
            }
        }

        try {
            ChannelEnterNameMgr.checkActivity();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }

        ChannelEnterNameRankMgr.saveEnterNameRank();
        ChannelEnterNameRankMgr.saveEnterNameGroupRank();

        //散财检测
        for (Map.Entry<Integer, EnterNameModel> modelEntry : ChannelEnterNameMgr.getEnterNameModelMap().entrySet()) {
            int activityId = modelEntry.getKey();
            if(doneDisperseGold.contains(activityId)){
                continue;
            }

            EnterNameModel model = modelEntry.getValue();

            //进入领奖期间5分钟
            if(!ChannelEnterNameMgr.activityInCanRewardPeriod(model.getActivityInfo())){
                continue;
            }

            EnterNameActivity activity = ChannelEnterNameMgr.getEnterNameActivity(activityId);
            if(activity == null){
                return;
            }

            doneDisperseGold.add(activityId);
            logger.info("activity {} disperse gold ", activityId);

            // channelId serverId  matchId  userId
            Map<Integer, Map<Long, Map<Integer, List<Long>>>>  nameMap = model.getChannelServerGroupMap();

            // 消息太多
            // 会丢失
            int msgCount = 0;
            for (Map.Entry<Integer, Map<Long, Map<Integer, List<Long>>>> chanelEntry : nameMap.entrySet()) {
                int channelId = chanelEntry.getKey();
                for (Map.Entry<Long, Map<Integer, List<Long>>> serverEntry : chanelEntry.getValue().entrySet()) {
                    long serverId = serverEntry.getKey();
                    for (Map.Entry<Integer, List<Long>> matchEntry : serverEntry.getValue().entrySet()) {
                        int matchId = matchEntry.getKey();
                        if(matchEntry.getValue().size() == 0){
                            continue;
                        }
                        EnterNameProto.ChannelEnterNameDisperseGoldSyncMsg.Builder sync = EnterNameProto.ChannelEnterNameDisperseGoldSyncMsg.newBuilder();
                        sync.setActivityId(activityId);
                        sync.setServerId(serverEntry.getKey());
                        sync.addAllUserId(matchEntry.getValue());

                        EnterNameGroupRankModel rankModel = ChannelEnterNameRankMgr.getEnterNameGroupRankModel(activityId, activity.getGroupConditionType(), matchId);
                        if(rankModel == null){
                            logger.info("activity {} disperse gold matchId {} rankModel is null ", activityId, matchId);
                            continue;
                        }
                        for (EnterNameGroupRank groupRank : rankModel.getRankList()) {
                            EnterNameProto.EnterNameDisperseGoldGroupInfoMsg.Builder builder = EnterNameProto.EnterNameDisperseGoldGroupInfoMsg.newBuilder();
                            builder.setScore(groupRank.getValue().longValue());
                            ActivityGroupMatch groupMatch = model.getMatchMap().get(groupRank.getGroupId());
                            if(groupMatch != null){
                                builder.addAllZoneList(groupMatch.getZoneIdList());
                            }else {
                                logger.info("activity {} disperse gold matchId {} groupId {} zone is null ", activityId, matchId, groupRank.getGroupId());
                            }
                            sync.addPk(builder);
                        }
                        ChannelMessageHelper.sendGamePacket(Protocol.S_ENTER_NAME_DISPERSE_GOLD_SYNC_FROM_CHANNEL, sync, channelId, serverId, 0);
                        logger.info("activity {} disperse gold to channel {}, server {}, matchId {} ", activityId, channelId, serverId, matchId);
                        msgCount++;
                        if(msgCount % 1000 == 0){
                            try{
                                Thread.sleep(10);
                            }catch (Exception e){
                                ChannelEnterNameMgr.getLogger().error("", e);
                            }
                        }
                    }
                }
            }

        }
    }
}
